﻿using Candy.Infrastructure;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Threading;
using System;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Candy.ViewModel
{
    public class UpdateViewModel : CandyViewModelBase
    {

        private string _releaseNotes;
        public string ReleasNotes
        {
            get
            {
                return _releaseNotes;
            }
            set
            {
                _releaseNotes = value;
                RaisePropertyChanged("ReleasNotes");
            }
        }


        private bool _isBusy;
        public bool IsBusy
        {
            get
            {
                return _isBusy;
            }
            set
            {
                _isBusy = value;
                RaisePropertyChanged("IsBusy");
            }
        }

        private bool _updateAvailable;
        public bool UpdateAvailable
        {
            get
            {
                return _updateAvailable;
            }
            set
            {
                _updateAvailable = value;
                RaisePropertyChanged("UpdateAvailable");
            }
        }


        INavigationService _navigationService;
        public UpdateViewModel(INavigationService navigationService)
        {
            if (IsInDesignMode)
            {
                _isBusy = true;
                _updateAvailable = true;
                _releaseNotes = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sollicitudin vehicula molestie. Suspendisse potenti. Aliquam quis nulla nisi, nec aliquet nibh. Quisque nisi dolor, rutrum in molestie vel, tincidunt placerat quam. Aenean sed diam ut eros porttitor varius. Donec mattis dignissim ultricies. Maecenas sit amet venenatis sapien. Nunc faucibus placerat lorem, eu ultricies nisl mattis ac. Mauris sodales, leo auctor mattis molestie, mauris quam pulvinar metus, at cursus erat augue sed ante. Donec suscipit ornare condimentum. Cras ultrices iaculis accumsan. Phasellus malesuada nisl vestibulum urna iaculis in vehicula eros tempor. Nam eros ipsum, porta et vulputate eu, auctor non odio. ";
            }
            _navigationService = navigationService;
        }



        private RelayCommand _checkFOrUpdate;
        public RelayCommand CheckForUpdate
        {
            get
            {
                return _checkFOrUpdate ?? (_checkFOrUpdate = new RelayCommand(ExecCheckForUpdate, CanCheckForUpdate));
            }
        }

        /// <summary>
        /// Checks whether the CheckForUpdate command is executable
        /// </summary>
        private bool CanCheckForUpdate()
        {
            return true;
        }

        /// <summary>
        /// Executes the CheckForUpdate command 
        /// </summary>
        private void ExecCheckForUpdate()
        {
            if (App.Current.IsRunningOutOfBrowser)
            {
                IsBusy = true;
                App.Current.CheckAndDownloadUpdateCompleted += (s, e) =>
                    {

                        if (e.Error != null)
                        {
                            MessageBox.Show(e.Error.Message);
                        }
                        if (e.UpdateAvailable)
                        {
                           

                            System.Net.WebClient wc = new System.Net.WebClient();
                            wc.OpenReadCompleted += (s2, e2) =>
                            {
                                if (e2.Error == null)
                                {
                                    System.IO.StreamReader sr = new System.IO.StreamReader(e2.Result);
                                    DispatcherHelper.CheckBeginInvokeOnUI(() =>
                                        {
                                            
                                            ReleasNotes = sr.ReadToEnd();
                                        });
                                }
                                DispatcherHelper.CheckBeginInvokeOnUI(() =>
                                {
                                    IsBusy = false;
                                    UpdateAvailable = true;
                                });
                            };
                            wc.OpenReadAsync(new Uri("../ChangeLog.txt", UriKind.Relative));
                        }
                        else
                        {
                            _navigationService.Navigate(NavigationTargets.Projects);
                        }
                    };

                App.Current.CheckAndDownloadUpdateAsync();
            }
            else
            {
                _navigationService.Navigate(NavigationTargets.Projects);
            }
        }

    }
}
